import mongoose from 'mongoose'
import validator from 'validator'
import bcrypt from 'bcrypt'
// const isEmail = require('validator/lib/isEmail')
import Unauthorized from '../errors/unauthorized'

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: validator.isEmail,
    },
  },
  password: {
    type: String,
    required: true,
    select: false,
  },
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 30,
  },
  accessLevel: {
    type: String,
    required: true
  }
})

userSchema.statics.findUserByCredentials = function findOne(email, password) {
  return this.findOne({ email }).select('+password')
    .then((user) => {
      if (!user) {
        return Promise.reject(new Unauthorized('Неправильные почта или пароль'))
      }

      return bcrypt.compare(password, user.password)
        .then((matched) => {
          if (!matched) {
            return Promise.reject(new Unauthorized('Неправильные почта или пароль'))
          }
          return user
        })
    })
}

export default mongoose.model('user', userSchema)
